<?php 

require_once 'database.php';

$objReturn = array();

//user to register
$strUsername = $_POST['username'];
//password to save
$strPassword = $_POST['password'];

//Determine if user exists
$dbUsers = mysql_query("SELECT * FROM account WHERE username= '$strUsername'", $dbLocalhost) 
	or die("Problem reading table: " . mysql_error());

$intUsersFound = mysql_num_rows($dbUsers);
//If not add user to DB and login the user

if($intUsersFound > 0){
	//Return error message 'username already exists!'
	$objReturn['code'] = 'ERROR';
	$objReturn['message'] = "Username already exists!";
} else {
	
	//since username doesnt exist, insert user into database
    $insert = "INSERT INTO account (username, password) VALUES ('$strUsername', '$strPassword')";
    $add_member = mysql_query($insert);
	//start the session
	//eol: I could be wrong, but I believe session_start() usually needs to come much earlier than this (probably before the html in index.php)
	session_start();

	$_SESSION['user'] = $strUsername;

	$objReturn['code'] = 'SUCCESS';
}

//Included to return JSON
header("content-type:application/json");
echo json_encode($objReturn);

?>